#!/usr/bin/python
# -*- coding: utf-8 -*-

# @date: 2022/1/12 17:28

# @Author : wuhuanbuai
# @Email : 877196754@qq.com
# @File : TAPD_M.py
import json,requests
import urllib
import os
import time

from requests.packages.urllib3.exceptions import InsecureRequestWarning
requests.packages.urllib3.disable_warnings(InsecureRequestWarning)

from selenium import webdriver
from tapd_conf import *

from bs4 import BeautifulSoup


class Tapd_Action():
    def __init__(self):
        self.driver = webdriver.PhantomJS(executable_path='./phantomjs.exe')
        self.s=requests.Session()
        self.headers={
            'User-Agent': 'Mozilla/5.0 (Windows NT 6.1; Win64; x64; rv:90.0) Gecko/20100101 Firefox/90.0',
        }
        self.s.verify=False
        self.s.headers=self.headers
        self.organization_id=TAPD_ORGANIZATION_ID

    def Login(self):
        self.driver.get('https://www.tapd.cn/cloud_logins/login')
        usename=self.driver.find_element_by_id('username')
        usename.send_keys(TAPD_USER)
        password=self.driver.find_element_by_id('password_input')
        password.send_keys(TAPD_PASSWORD)
        submit=self.driver.find_element_by_id('tcloud_login_button')
        submit.click()
        if TAPD_IF_LOGIN:
            #todo 判断是否登录比较耗时，去掉
            self.driver.get('https://www.tapd.cn/%s/workspaces/workspace_edit' % TAPD_ORGANIZATION_ID_SHORT)
            title=self.driver.find_element_by_xpath('//*[@id="ws-sidebar"]/div//span')
            if TAPD_COM_NAME in title.text:
                print('登录成功')
            else:
                print("登录失败")
        Cookies={}
        cook=self.driver.get_cookies()
        print(cook,type(cook))
        for keys in cook:
            Cookies[keys['name']]=keys['value']
        self.cook=Cookies
        print(self.cook)
        with open("./TAPDCookies.txt",'w') as f:
            f.write(json.dumps(self.cook))
        print('重新生成cookies文件')

    def iF_login(self):
        loginstatusurl =TAPD_COM_URL
        if os.path.exists("./TAPDCookies.txt"):
            #self.s.cookies.clear_session_cookies()
            with open("./TAPDCookies.txt", "r") as f:
                self.cook = json.loads(f.read())
                loginstatus = self.s.get(loginstatusurl, cookies=self.cook, allow_redirects=False, verify=False)
                if loginstatus.status_code!=200:
                    self.Login()
                else:
                    print('已经登录')
                requests.utils.add_dict_to_cookiejar(self.s.cookies,self.cook)
                return True
        else:
            self.Login()

    def get_screen(self,filename='截图.png'):
        self.driver.save_screenshot(filename=filename)

    def close(self):
        self.driver.close()

    def search_User(self,nick=None,name=None,email=None,member_status=('normal','inactive','dission')):
        '''
        :param nick: 昵称
        :param name: 真实姓名
        :param email: 邮箱
        :param member_status: 人员状态，默认=('normal','inactive','dission')
        :return: [{'id': '158115589', 'nick': '王涛', 'name': '王涛', 'email': 'wangt@***.com', 'qywx': 'KD01***', 'dept-name': '研发二部', 'role': '公司普通成员', 'status': '在职'},]
        '''
        search_arg=''
        if nick:
            search_arg+='data[Filter][nick]='+nick+'&'
        if name:
            search_arg+='data[Filter][name]='+name+'&'
        if email:
            search_arg+='data[Filter][email]='+email+'&'
        search_arg+='qksearch=true'+'&'
        for member in member_status:
            search_arg+='data[member_status][]='+member+'&'
        search_arg+='organization_id='+TAPD_ORGANIZATION_ID+'&'
        search_arg+='page=1'+'&'
        current_milli_time = str(round(time.time() * 1000))
        search_arg+='t='+current_milli_time
        #print(search_arg)
        #search_arg=urllib.parse.quote(search_arg)
        #print('编码后：'+search_arg)
        url='https://www.tapd.cn/%s/settings/ajax_get_company_member_list/?' % TAPD_ORGANIZATION_ID_SHORT
        res=self.s.get(url=url+search_arg)
        #print(res.text)
        soup = BeautifulSoup(res.text,'lxml')
        u_list=soup.find(id="member-list-table").tbody.find_all('tr')
        #print(u_list)
        resJson=[]
        if u_list:
            for user in u_list:
                userJson={}
                userJson['member_id']=user.find(class_='idx')['value']
                userJson['user_id']=user.find(class_='j-editable-qy-userid')['data-user-id']
                userJson['nick']=user.find(class_='member-user-nick').get_text()
                userJson['name']=user.find(class_='member-name-div').get_text().strip()
                userJson['email']=user.find(class_='member-email-div').get_text().strip()
                userJson['qywx']=user.find(class_='j-editable-qy-userid')['data-editable-value']
                userJson['gender']=user.select_one('td:nth-child(9) div').get_text().strip()
                userJson['position']=user.find(class_='position-div').get_text().strip()
                userJson['dept-name']=user.find(class_='dept-name').get_text().strip()
                userJson['role_id']=user.find(class_='member-role-div').parent['data-editable-value']
                userJson['role_name']=user.find(class_='member-role-div').get_text().strip()
                userJson['status']=user.select_one('td>span').get_text().strip()
                resJson.append(userJson)
        #获取人员基本信息完毕
        print(resJson)
        return resJson

    def get_roles(self):
        '''获取权限列表
        :param 无
        :return [{'id': '1000000000000000001', 'role-name': '公司管理员'}, {'id': '1000000000000000090', 'role-name': '公司普通成员'}, {'id': '1122674031001001996', 'role-name': '统计管理'}, {'id': '1122674031001000738', 'role-name': '创建模板'}, {'id': '1122674031001002824', 'role-name': '客服质量'}, {'id': '1122674031001000526', 'role-name': '开发测试'}, {'id': '1122674031001001558', 'role-name': '项目经理'}, {'id': '1122674031001003891', 'role-name': '项目创建人'}, {'id': '1122674031001000320', 'role-name': '项目管理员'}]
        :returns 权限名称与对应角色'''
        url='https://www.tapd.cn/%s/roles' % TAPD_ORGANIZATION_ID_SHORT
        res=self.s.get(url=url)
        #print(res.text)
        soup = BeautifulSoup(res.text,'lxml')
        r_list=soup.find(id="role-list-ul").find_all('li')
        resJson=[]
        if r_list:
            for role in r_list:
                roleJson={}
                roleJson['id']=role['data-role-id']
                roleJson['role-name']=role.find('span',class_='role-name')['title']
                resJson.append(roleJson)
        print(resJson)
        return resJson

    def set_roles_name(self,user,name=None,role_id=None,nick=None):
        '''设置角色和真实用户名
        :param user 用户搜索返回.
        :param name str 真实姓名
        :param role_id str "1000000000000000090|1122674031001003891"
        :return 1或者0 1成功，其他失败'''
        url='https://www.tapd.cn/%s/settings/inline_update?r=%s' % (TAPD_ORGANIZATION_ID_SHORT,str(round(time.time() * 1000)))
        postDate={}
        headers={}
        resJson={}
        headers['Accept']='*/*'
        headers['Accept-Language']='zh-CN,zh;q=0.9'
        headers['Content-Type']='application/x-www-form-urlencoded; charset=UTF-8'
        headers['DSC-TOKEN']=self.cook['dsc-token']
        headers['Referer']='https://www.tapd.cn/22674031/settings/team'
        headers['Host']='www.tapd.cn'
        headers['X-Requested-With']='XMLHttpRequest'
        if user:
            postDate['data[target_nick]']=user['nick']
            postDate['data[target_user_id]']=user['user_id']
            postDate['data[target_email]']=user['email']
            if name:
                postDate['data[field]']='name'
                postDate['data[value]']=name
                user['name']=name
                print(postDate)
                #print(url)
                #print(self.s.headers)
                res=self.s.post(url=url,data=postDate,headers=headers)
                print(res.text)
                resJson['name']=res.text
            if role_id:
                postDate['data[field]']='role_id'
                postDate['data[value]']=role_id
                user['role_id']=role_id
                print(postDate)
                #print(url)
                #print(self.s.headers)
                res=self.s.post(url=url,data=postDate,headers=headers)
                print(res.text)
                resJson['role_id']=res.text
            if nick:
                postDate_Nick={}
                postDate_Nick['data[nick]']=nick
                postDate_Nick['data[name]']=user['name']
                postDate_Nick['data[gender]']='1' if user['gender']=='男' else '0' if user['gender']=='女' else '--'
                postDate_Nick['data[position]']=user['position']
                postDate_Nick['data[role_id][]']=user['role_id']
                postDate_Nick['data[user_id]']=user['user_id']
                postDate_Nick['data[member_id]']=user['member_id']
                postDate_Nick['dsc_token']=self.cook['dsc-token']
                print(postDate_Nick)
                url='https://www.tapd.cn/%s/settings/cloud_edit_user_info/%s' % (TAPD_ORGANIZATION_ID_SHORT,user['member_id'])
                res=self.s.post(url=url,data=postDate_Nick,headers=headers)
                print(res.text)
                soup = BeautifulSoup(res.text,'lxml')
                message=soup.find(id='flashMessage').get_text()
                resJson['nick']=message
        print(resJson)
        return resJson


if __name__ == '__main__':
    tapd=Tapd_Action()
    tapd.iF_login()
    uList=tapd.search_User(email='ruanyiqi',member_status=('normal','inactive'))
    for u in uList:
        if u['email']=='ruanyiqi':
            user=u
            break
    # tapd.get_roles()
    # print(user)
    if user:
        tapd.set_roles_name(user=user,role_id='1000000000000000090',nick='阮')
    tapd.close()